document.getElementById('translate').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { action: "getSelectedText" }, (response) => {
      if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
        document.getElementById('inputText').value = "Error: Could not retrieve text.";
      } else {
        document.getElementById('inputText').value = response.text || "No text selected.";
      }
    });
  });
});

document.getElementById('execute').addEventListener('click', () => {
  const inputElement = document.getElementById('inputText');
  if (inputElement) {
    const text = inputElement.value;
    const actionElement = document.querySelector('input[name="action"]:checked');
    const action = actionElement ? actionElement.value : 'translate';
    callKimiApi(text, action);
  } else {
    console.error("Element with ID 'inputText' not found.");
  }
});

function callKimiApi(text, action) {
  const apiUrl = "https://api.moonshot.cn/v1/chat/completions"; // Correct endpoint for model interaction
  const apiKey = "sk-Blt9B9TSbgxR55Op7lURwvZJyiSaGdNrnUx0LyEeop7ATpaF"; // Replace with your actual Kimi API key

  fetch(apiUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model: "moonshot-v1-8k", // Specify the model
      messages: [
        {"role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手。"},
        {"role": "user", "content": text} // Use the input text as the user prompt
      ],
      temperature: 0.3
    })
  })
  .then(response => {
    if (!response.ok) {
      console.error(`HTTP error! Status: ${response.status}`);
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log("Full API Response:", data);
    // Assuming the response structure might be different, adjust accordingly
    const result = data.result || data.translation || data.output; // Adjust based on actual response structure
    if (result) {
      document.getElementById('result').innerText = `Result for ${action}: ${result}`;
    } else {
      document.getElementById('result').innerText = "Unexpected API response format.";
    }
  })
  .catch(error => {
    console.error("Error calling Kimi API:", error);
    document.getElementById('result').innerText = "Error calling Kimi API.";
  });
} 